package com.horizon.im.imServer.serverHandler;

import com.horizon.concurrent.CallBackTask;
import com.horizon.concurrent.CallBackTaskScheduler;
import com.horizon.im.common.bean.msg.ProtoMsg;
import com.horizon.im.imServer.server.session.LocalSession;
import com.horizon.im.imServer.server.session.service.SessionManager;
import com.horizon.im.imServer.serverProcessor.LoginProcessor;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Data
@ChannelHandler.Sharable
@Service("LoginRequestHandler")
public class LoginRequestHandler extends ChannelInboundHandlerAdapter {
    @Autowired
    LoginProcessor loginProcessor;
    @Autowired
    private ChatRedirectHandler chatRedirectHandler;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (null == msg || !(msg instanceof ProtoMsg.Message))
        {
            super.channelRead(ctx, msg);
            return;
        }

        ProtoMsg.Message pkg = (ProtoMsg.Message) msg;

        //取得请求类型
        ProtoMsg.HeadType headType = pkg.getType();

        if (!headType.equals(loginProcessor.op()))
        {
            super.channelRead(ctx, msg);
            return;
        }


        LocalSession session = new LocalSession(ctx.channel());
        //异步任务处理登录
        CallBackTaskScheduler.add(new CallBackTask<Boolean>() {
            @Override
            public Boolean execute() throws Exception {
                return loginProcessor.action(session, pkg);
            }

            //异步任务返回
            @Override
            public void onBack(Boolean aBoolean) {
                if (aBoolean) {
                    log.info("登录成功："+session.getUserDTO());
                    ctx.pipeline().addAfter("login", "chat", chatRedirectHandler);
                    ctx.pipeline().addAfter("login","heartBeat", new HeartBeatServerHandler());
                    ctx.pipeline().remove("login");
                } else {
                    SessionManager.getSingleInstance().closeSession(ctx);
                    log.info("登录失败:"+session.getUserDTO());
                }
            }

            @Override
            public void onException(Throwable t) {
                t.printStackTrace();
                log.info("登录失败："+session.getUserDTO());
                SessionManager.getSingleInstance().closeSession(ctx);

            }
        });
    }
}
